package com.app.service.imessage;

import com.app.model.response.RetCode;
import com.app.model.response.RetStatus;
import com.app.repository.interfaces.UserMapper;
import com.app.service.ResponseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lichaojie on 2017/8/6. It's a beautiful day.
 */
@Service
public class ImessageService {

    @Autowired
    private ResponseService responseService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IMService imService;

    public RetStatus getSig(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int userId = (int)paraMap.get("userId");
        if((long)userId > userMapper.getMaxId() || (long)userId < 1){
            return responseService.doResponse(218);
        }

//        String sig = imService.doMain(Integer.toString(userId));
//        if(sig == ""){
//            while(sig == ""){
//                sig = imService.doMain(Integer.toString(userId));
//            }
//        }
        String sig = computeSig((long)userId);

        Map<String,String> map = new HashMap<>();
        map.put("sig",sig);

        RetStatus retStatus = new RetStatus();
        retStatus.setCode(100)
                .setMessage(RetCode.getMessage(100))
                .setBody(map);

        return retStatus;
    }

    public String computeSig(long userId){
        String sig = imService.doMain(Long.toString(userId));
        if(sig == ""){
            while(sig == ""){
                sig = imService.doMain(Long.toString(userId));
            }
        }
        return sig;
    }


}
